package frog.lazy.framework.keeper.filter;

import frog.lazy.framework.core.exception.BizException;
import frog.lazy.framework.keeper.constant.JWTConstant;
import frog.lazy.framework.keeper.dto.AccountDTO;
import frog.lazy.framework.keeper.provider.IPermProvider;
import frog.lazy.framework.keeper.utils.JWTUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@AllArgsConstructor
public class JWTAuthFilter extends AbstractPathMatchingFilter{

    private JWTUtils jwtUtils;
    private IPermProvider permProvider;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        Subject subject = getSubject(request, response);
        HttpServletRequest req = (HttpServletRequest) request;
        String userToken = req.getHeader(JWTConstant.header_token);
        if("OPTIONS".equals(req.getMethod())) {
            return true;
        }
        AccountDTO accountDTO = jwtUtils.parseJwt(userToken);
        if(null == subject || !subject.isAuthenticated()) {
            subject.login(accountDTO);
        }
        String url = this.getPathWithinApplication(request).toLowerCase();
        String method = WebUtils.toHttp(request).getMethod().toUpperCase();
        return permProvider.check(accountDTO, url, method);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response){
        throw BizException.fail("没有权限");
    }

}
